<template>
  <el-dialog
      :model-value="visible"
      @update:model-value="$emit('update:visible', $event)"
      title="创建新活动"
      width="800px"
      :close-on-click-modal="false"
  >
    <el-form
        :model="formData"
        :rules="rules"
        ref="formRef"
        label-width="100px"
        label-position="right"
    >
      <!-- 活动标题 -->
      <el-form-item label="活动标题：" prop="title">
        <el-input v-model="formData.title" placeholder="请输入活动标题"/>
      </el-form-item>

      <!-- 活动描述 -->
      <el-form-item label="活动描述：" prop="description">
        <el-input
            v-model="formData.description"
            type="textarea"
            :rows="4"
            placeholder="请输入活动详细描述"
        />
      </el-form-item>

      <!-- 基地选择 -->
      <el-form-item label="活动基地：" prop="baseId">
        <el-select
            v-model="formData.baseId"
            placeholder="请选择活动基地"
            style="width: 100%"
        >
          <el-option
              v-for="base in baseList"
              :key="base.id"
              :label="base.name"
              :value="base.id"
          />
        </el-select>
      </el-form-item>

      <!-- 活动地址 -->
      <el-form-item label="活动地址：" prop="address">
        <el-input v-model="formData.address" placeholder="请输入活动地址"/>
      </el-form-item>

      <!-- 活动日期范围 -->
      <el-form-item label="活动日期：" prop="dateRange" class="time-range-item">
        <el-date-picker
            v-model="formData.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
        />
      </el-form-item>

      <!-- 开始时间 -->
      <el-form-item label="开始时间：" prop="startTime">
        <el-time-picker
            v-model="formData.startTime"
            placeholder="选择开始时间"
            format="HH:mm"
            value-format="HH:mm:ss"
            style="width: 100%"
        />
      </el-form-item>

      <!-- 报名截止时间 -->
      <el-form-item label="报名截止：" prop="registrationDeadline">
        <el-date-picker
            v-model="formData.registrationDeadline"
            type="datetime"
            placeholder="选择报名截止时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
        style="width: 100%"
        />
      </el-form-item>

      <!-- 发布 -->
      <el-form-item label="发布时间：" prop="publishTime">
        <el-date-picker
            v-model="formData.publishTime"
            type="datetime"
            placeholder="选择发布时间"
            value-format="YYYY-MM-DDTHH:mm:ss"
        style="width: 100%"
        />
      </el-form-item>

      <!-- 目标受众 -->
      <el-form-item label="目标受众：" prop="targetAudience">
        <el-input v-model="formData.targetAudience" placeholder="如：全体师生、高年级学生等"/>
      </el-form-item>

      <!-- 是否免费 -->
      <el-form-item label="是否免费：" prop="isFree">
        <el-radio-group v-model="formData.isFree">
          <el-radio :label="true">免费</el-radio>
          <el-radio :label="false">收费</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 最大参与人数 -->
      <el-form-item label="最大人数：" prop="maxParticipants">
        <el-input-number
            v-model="formData.maxParticipants"
            :min="1"
            :max="1000"
            placeholder="请输入最大参与人数"
            style="width: 100%"
        />
      </el-form-item>

      <!-- 当前参与人数 -->
      <el-form-item label="当前人数：" prop="currentParticipants">
        <el-input-number
            v-model="formData.currentParticipants"
            :min="0"
            :max="formData.maxParticipants || 1000"
            placeholder="当前参与人数"
            style="width: 100%"
        />
      </el-form-item>

      <!-- 创建人ID -->
      <el-form-item label="创建人ID：" prop="creatorId" v-if="false">
        <el-input v-model="formData.creatorId" disabled/>
      </el-form-item>

      <el-form-item class="form-actions">
        <el-button type="primary" @click="submitForm" :loading="loading">提交</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {ref, reactive, watch, computed} from 'vue';
import {ElMessage} from 'element-plus';
import {createUserActivity} from "@/api/teacher.js";

const props = defineProps({
  visible: Boolean,
  teacherList: {
    type: Array,
    default: () => []
  },
  baseList: {
    type: Array,
    default: () => []
  }
});

const emit = defineEmits(['update:visible', 'success']);

const formRef = ref(null);
const loading = ref(false);

const formData = reactive({
  title: '',
  description: '',
  baseId: '',
  baseName: '',
  address: '',
  startDate: '',
  endDate: '',
  totalDays: 0,
  startTime: '09:00:00',
  registrationDeadline: '',
  publishTime: '',
  targetAudience: '全体师生',
  isFree: true,
  maxParticipants: 50,
  currentParticipants: 0,
  creatorId: 1 // 默认值，实际应该从用户信息获取
});

// 计算总天数
const dateRange = computed({
  get: () => {
    if (formData.startDate && formData.endDate) {
      return [formData.startDate, formData.endDate];
    }
    return [];
  },
  set: (value) => {
    if (value && value.length === 2) {
      formData.startDate = value[0];
      formData.endDate = value[1];

      // 计算总天数
      const start = new Date(value[0]);
      const end = new Date(value[1]);
      const diffTime = Math.abs(end - start);
      formData.totalDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
    } else {
      formData.startDate = '';
      formData.endDate = '';
      formData.totalDays = 0;
    }
  }
});

const rules = {
  title: [
    {required: true, message: '请输入活动标题', trigger: 'blur'},
    {min: 2, max: 100, message: '长度在2到100个字符', trigger: 'blur'}
  ],
  description: [
    {required: true, message: '请输入活动描述', trigger: 'blur'}
  ],
  baseId: [
    {required: true, message: '请选择活动基地', trigger: 'change'}
  ],
  address: [
    {required: true, message: '请输入活动地址', trigger: 'blur'}
  ],
  dateRange: [
    {required: true, message: '请选择活动日期范围', trigger: 'change'}
  ],
  startTime: [
    {required: true, message: '请选择开始时间', trigger: 'change'}
  ],
  registrationDeadline: [
    {required: true, message: '请选择报名截止时间', trigger: 'change'}
  ],
  publishTime: [
    {required: true, message: '请选择发布时间', trigger: 'change'}
  ],
  targetAudience: [
    {required: true, message: '请输入目标受众', trigger: 'blur'}
  ],
  maxParticipants: [
    {required: true, message: '请输入最大参与人数', trigger: 'blur'}
  ]
};

// 监听基地选择，自动填充基地名称和地址
watch(() => formData.baseId, (newBaseId) => {
  if (newBaseId) {
    const selectedBase = props.baseList.find(base => base.id === newBaseId);
    if (selectedBase) {
      formData.baseName = selectedBase.name;
      // 如果地址为空，可以使用基地的默认地址
      if (!formData.address) {
        formData.address = selectedBase.address || '';
      }
    }
  } else {
    formData.baseName = '';
  }
});

// 设置默认时间
const setDefaultTimes = () => {
  const now = new Date();

  // 默认报名截止时间：活动开始前1天
  if (formData.startDate) {
    const startDate = new Date(formData.startDate);
    startDate.setDate(startDate.getDate() - 1);
    startDate.setHours(18, 0, 0); // 下午6点
    formData.registrationDeadline = startDate.toISOString().replace('T', ' ').substring(0, 19);
  }

  // 默认发布时间：当前时间
  formData.publishTime = now.toISOString().replace('T', ' ').substring(0, 19);
};

// 监听开始日期变化，自动设置截止时间
watch(() => formData.startDate, (newStartDate) => {
  if (newStartDate) {
    setDefaultTimes();
  }
});

// 在 ActivityForm.vue 中修改日期格式化
const submitForm = async () => {
  try {
    await formRef.value.validate();
    loading.value = true;

    // 获取用户信息
    const userInfoStr = localStorage.getItem('userInfo');
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : { id: 1 };

    // 从 dateRange 中提取 startDate 和 endDate
    let startDate = '';
    let endDate = '';
    let totalDays = 0;

    if (formData.dateRange && formData.dateRange.length === 2) {
      startDate = formData.dateRange[0];
      endDate = formData.dateRange[1];

      // 计算总天数
      const start = new Date(startDate);
      const end = new Date(endDate);
      const diffTime = Math.abs(end - start);
      totalDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)) + 1;
    }

    // 格式化日期时间为后端期望的格式
    const formatDateTime = (dateTimeStr) => {
      if (!dateTimeStr) return null;

      // 如果已经是 ISO 格式，直接返回
      if (dateTimeStr.includes('T')) {
        return dateTimeStr;
      }

      // 将 "YYYY-MM-DD HH:mm:ss" 转换为 "YYYY-MM-DDTHH:mm:ss"
      return dateTimeStr.replace(' ', 'T');
    };

    // 构建提交数据
    const activityData = {
      title: formData.title,
      description: formData.description,
      baseId: formData.baseId,
      baseName: formData.baseName,
      address: formData.address,
      startDate: startDate,
      endDate: endDate,
      totalDays: totalDays,
      startTime: formData.startTime,
      registrationDeadline: formatDateTime(formData.registrationDeadline),
      publishTime: formatDateTime(formData.publishTime),
      targetAudience: formData.targetAudience,
      isFree: formData.isFree,
      maxParticipants: formData.maxParticipants,
      currentParticipants: formData.currentParticipants,
      creatorId: userInfo.id
    };

    console.log('提交的数据:', JSON.stringify(activityData, null, 2));

    // 验证必填字段
    if (!activityData.startDate || !activityData.endDate) {
      ElMessage.error('请选择活动日期范围');
      loading.value = false;
      return;
    }

    // 调用创建活动API
    const result = await createUserActivity(activityData);

    if (result.success) {
      ElMessage.success('活动创建成功');
      emit('success', result.data);
      closeDialog();
    } else {
      ElMessage.error(result.message || '创建失败，请重试');
    }

  } catch (error) {
    loading.value = false;
    console.error('表单提交错误:', error);
    ElMessage.error('提交失败，请重试');
  } finally {
    loading.value = false;
  }
};



const closeDialog = () => {
  emit('update:visible', false);
  resetForm();
};

const resetForm = () => {
  formRef.value?.resetFields();
  // 手动重置一些特殊字段
  Object.assign(formData, {
    title: '',
    description: '',
    baseId: '',
    baseName: '',
    address: '',
    startDate: '',
    endDate: '',
    totalDays: 0,
    startTime: '09:00:00',
    registrationDeadline: '',
    publishTime: '',
    targetAudience: '全体师生',
    isFree: true,
    maxParticipants: 50,
    currentParticipants: 0,
    creatorId: 1
  });
};

// 监听对话框显示状态，初始化表单
watch(() => props.visible, (newVisible) => {
  if (newVisible) {
    // 设置默认发布时间为当前时间
    const now = new Date();
    formData.publishTime = now.toISOString().replace('T', ' ').substring(0, 19);
  }
});
</script>

<style scoped>
/* 表单标签样式 */
:deep(.el-form-item__label) {
  text-align: right;
  padding-right: 12px;
  font-weight: 500;
}

/* 时间范围选择器 */
.time-range-item :deep(.el-date-editor) {
  width: 100%;
}

/* 表单操作按钮 */
.form-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

/* 数字输入框样式 */
:deep(.el-input-number) {
  width: 100%;
}

/* 对话框内容区域 */
:deep(.el-dialog__body) {
  padding: 20px 30px;
  max-height: 70vh;
  overflow-y: auto;
}

/* 文本域样式 */
:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 80px;
}

/* 单选框组样式 */
:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}
</style>
